﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace KSWSClient.Code.Util
{
    public class ClientUtil
    {
        // 配置文件路径
        public const string CONFIG_PATH = "Xml/KClientConfig.xml";
        public const string XPATH_SERVER_HOST = "/Config/ServerHost";
        public const string XPATH_SERVER_PORT = "/Config/ServerPort";
        public const string XPATH_CONTEXT_PATH = "/Config/ContextPath";
        public const string XPATH_USER_NAME = "/Config/UserName";
        public const string XPATH_PASSWORD = "/Config/Password";
        // 写入数据到配置文件
        public static bool WriteConfig(string serverHost,string port,string context,string username,string password)
        {
            bool resultCode = false;
            try
            {
                XmlNode root = GetRootNode();
                XmlNode configNode = root.SelectSingleNode(XPATH_SERVER_HOST);
                configNode.InnerText = serverHost;
                configNode = root.SelectSingleNode(XPATH_SERVER_PORT);
                configNode.InnerText = port;
                configNode = root.SelectSingleNode(XPATH_CONTEXT_PATH);
                configNode.InnerText = context;
                configNode = root.SelectSingleNode(XPATH_USER_NAME);
                configNode.InnerText = username;
                configNode = root.SelectSingleNode(XPATH_PASSWORD);
                configNode.InnerText = password;
                root.OwnerDocument.Save(CONFIG_PATH);
                resultCode = true;
            }catch (Exception)
            {
                resultCode = false;
            }
            return resultCode;
        }
        // 根据xPath获取配置文件里面的值
        public static string GetNodeValue(string xPath)
        {
            XmlNode root = GetRootNode();
            if (root == null)
            {
                return String.Empty;
            }
            return root.SelectSingleNode(xPath).InnerText;
        }
        // 获取配置文件的根节点
        private static XmlNode GetRootNode()
        {
            XmlReader reader = null;
            FileInfo file = new FileInfo(CONFIG_PATH);
            if (file.Exists)
            {
                reader = new XmlTextReader(CONFIG_PATH);
            }
            if (reader == null)
            {
                return null;
            }
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            XmlNode root = doc.DocumentElement;
            return root;
        }
    }
}
